#!/usr/bin/python 
#-*- coding=utf-8 -*-

import tornado.ioloop
import tornado.web
import logging

from handler.DataHandler import DataHandler
from handler.IDGenerator import IDGenerator
from pymongo import MongoClient
import socket, platform
import zc.zk

class Server():
    def __init__(self, conf):
        self.conf = conf
        self.logger = logging.getLogger('broker')
        self.role = conf.get('broker', 'role')
        self.port = conf.get('broker', 'server-port')

    def start(self):
        # register to server
        meta_server = self.conf.get('broker', 'meta-server')
        logging.debug('get meta server: %s' % meta_server)
        self.zk = zc.zk.ZooKeeper(meta_server)
        broker_ip = socket.gethostbyname(platform.node())
        broker_port = self.conf.get('broker', 'server-port')
        try:
            self.zk.register_server('/iotmq/ds-group', (broker_ip, broker_port))
            logging.info('register server success')
        except Exception, e:
            logging.exception('register server failed, %s' % str(e))

        db = None
        idg = IDGenerator()
        try:
            conn = MongoClient('127.0.0.1', 27017)
            db = conn['iotmq']
            self.logger.info('connect to db OK')
        except Exception, e:
            self.logger.error('connect to db failed, %s' % str(e))
            exit

        app = tornado.web.Application([
                (r'/([0-9a-zA-Z\-]+)/([0-9a-zA-Z\-]+)/([0-9\-]*)', DataHandler, dict(db = db,
                                                                                     idg = idg,
                                                                                     conf = self.conf)),
                ])
        app.listen(self.port)
        self.logger.info('server start to listen...')
        tornado.ioloop.IOLoop.instance().start()

if __name__ == '__main__':
    from ConfigParser import ConfigParser
    formatstr = '%(asctime)s %(name)-8s %(levelname)-8s %(message)s'
    logging.basicConfig(level = logging.DEBUG, format = formatstr)
    conf = ConfigParser()
    conf.read('./conf/broker.conf')
    s = Server(conf)
    s.start()
